<?php
namespace app\index\controller;
use think\exception\HttpResponseException;
use think\Response;
use think\Config;
use think\Session;
use app\common\controller\Frontend;
use app\common\model\Subject;
use app\common\model\Knowledge;
use app\common\model\Exam;
use app\common\model\Account;
use app\common\model\Worker;

class Index extends Frontend{
    public function index(){
        $subject = Subject::where('status',1)->order('sort asc')->select();
        foreach ($subject as $key => &$value) {
            $value['list'] = Knowledge::where('status',1)->where('subject_id',$value['id'])->order('sort asc')->select();
        }
        $this->account['workers'] = [ '1_1'=>95,'1_2'=>75];
        $this->assign('account',$this->account);
        $this->assign('subject', $subject);
        return $this->fetch();
    }

    public function player($id){
        $info = Knowledge::get($id);
        cache('targetExam_'.$this->account['id'].'_id',null);
        cache('variantsExa_'.$this->account['id'].'_id',null);
        cache('targetExamAsk_'.$this->account['id'].'_id',null);
        cache('variantsAsk_'.$this->account['id'].'_id',null);
        $this->assign('info', $info);
        return $this->fetch();
    }
   
     /**
      * 人工题检测
      */
     public function worker(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $worker = new Worker();
            $worker->exam_id = $data['id'];
            $worker->account_id = $this->account['id'];
            $worker->fruit = $data['fruit'];
            $worker->save($data);
            $this->success('保存成功',null,$worker['id']);
        }else{
            $id = $this->request->get('id');
            $worker = Worker::get($id);
            if($worker->result == 0){
                $this->error();
            }
            $exam = Exam::get($worker->exam_id);
            $result =$exam->toArray();
            $result['result'] = $worker->result;
            $result['image'] = $worker->image;
            $result['video'] = $worker->video;
            $this->success('result',null, $result);
        }
     }
    /**
     * 目标获取
     */
    public function target(){//fruit,result;
        if($this->request->isPost()){//顺序获题
            $id = $this->request->get('id');
            $data = $this->request->post();
        
            if(!cache('targetExam_'.$this->account['id'].'_id') && !cache('targetExamAsk_'.$this->account['id'].'_id')){ 
                $exam = Exam::where('knowledge_id',$id)->where('status',1)->where('type_id',1)->select();
                $targetExam = [];
                if(!empty($exam)){
                    foreach ($exam as $key => $value) {
                        if($value['cate']=='4' || $value['cate']=='5'){
                            cache('targetExam_isverify',true);
                        }
                        $targetExam[] = $value->toArray();
                    }
                }
                cache('targetExam_'.$this->account['id'].'_id',$targetExam);
            }else{
                $targetExam = cache('targetExam_'.$this->account['id'].'_id');
            }
            //存储答案
            if(!empty($data)){
                $targetExamAsk = cache('targetExamAsk_'.$this->account['id'].'_id');
                $targetExamAsk[]=$data;
                cache('targetExamAsk_'.$this->account['id'].'_id',$targetExamAsk);  
            }
            $more = true;
            if(empty($targetExam)){
                $more = false;
            }else{
                $result = array_shift($targetExam);
                cache('targetExam_'.$this->account['id'].'_id',$targetExam);
            }
            
            if($more){
                $this->success('获取成功',null,$result);
            }else{
                $targetExamAsk = cache('targetExamAsk_'.$this->account['id'].'_id');
                $score = $this->examadd($targetExamAsk,$id,'target');
                $callback = [
                    'type' => 'target',
                    'score' => $score['rate'],
                    'result'=> $score['result'],
                    'is_pass'=> config('site')['target_rate'] <= $score['rate']?1:0,
                ];
                $this->error('没有更多题目了',null,$callback);
            }
            
            
        }
    }
    

    /**
     * 变获取
     */
    public function variants(){
        if($this->request->isPost()){//顺序获题
            $id = $this->request->param('id');
            $data = $this->request->param('data');
            $variants = [];
            $the_type = '';
            if(!cache('variantsExa_'.$this->account['id'].'_id') &&!cache('variantsAsk_'.$this->account['id'].'_id')){
                $Exams = Exam::where('knowledge_id',$id)->where('status',1)->where('type_id','>',1)->select();//变式
                if(!empty($exam)){
                    foreach ($Exams as $key => $value) {
                        if($key == 0){
                            $the_type = 'type_'.$value['type_id'];
                        }
                        $variants['type_'.$value['type_id']][] = $value;
                    }
                    cache('variantsExa_'.$this->account['id'].'_id',$variants);
                }
            }else{
                $variants =cache('variantsExa_'.$this->account['id'].'_id');
            }
            //答案
            if(!empty($data)){
                $variantAsk = cache('variantsAsk_'.$this->account['id'].'_id');
                $variantAsk[]=$data;
                cache('variantsAsk_'.$this->account['id'].'_id',$variantAsk); 
            }
            if($data['result'] == 1){
                $newdata = $data;
                unset($newdata['result']);
                unset($newdata['fruit']);
                $variants['type_'.$data['type_id']][] = $newdata;
                $result = array_shift($variants['type_'.$data['type_id']]);
            }
            $more = true;
            if($data['result'] == 2){//
                unset($variants['type_'.$data['type_id']]);
                if(count($variants)>0){
                    $keys = array_keys($variants); // 获取所有键名
                    $result = array_shift($variants[$keys[0]]);
                }else{
                    $more = false;
                }
            }
            if(!$more){//没有更多
                $variantAsk = cache('variantsAsk_'.$this->account['id'].'_id');
                $score = $this->examadd($variantAsk,$id,'variants');
                $callback = [
                    'type' => 'variants',
                    'score' => $score['rate'],
                    'result'=> $score['result'],
                    'is_pass'=> config('site')['target_rate'] <= $score['rate']?1:0,
                ];
                $this->error('没有更多题目了',null,$callback);
            }else{
                $this->success('获取成功',null,$result);
            }
        }
    }

    protected function examadd($data,$id,$type){//
        $homework = [];
        $right = 0;
        $result = [];
        foreach ($data as $key => $value) {
            if($value['result'] == 2){
                $right++;
            }
            $result[] = $value['result'];
            $homework[] = [
                'account_id'=>$this->account['id'],
                'cate'=>$value['cate'],//1填空题，2单选，3多选，4简答题，5计算题
                'knowledge_id'=>$id,
                'exam_id'=>$value['id'],
                'result'=>$value['result'],
                'worker_id'=>isset($value['worker_id'])?$value['worker_id']:0,
                'fruit'=>$value['cate'] == 1?json_encode($value['fruit']):$value['fruit'],//填空题
                'answer'=>json_encode($value['answer']),//答案
                'type'=>$type
            ];
        }
        model('Homework')->where('account_id',$this->account['id'])->where('knowledge_id',$id)->where('type',$type)->delete();
        model('Homework')->saveAll($homework);
        $rate = intval($right/count($data)*100);
        //variants重置account
        if($type == 'variants'){
            $knowledge = Knowledge::get($homework[0]['knowledge_id']);
            $workers = $knowledge['subject_id'].'_'.$knowledge['id'];
            $accountWorkers = $this->account['workers'];
            $account = Account::get($this->account['id']);
            $accountWorkers[$workers] = $rate;
            $account->workers = $accountWorkers;
            $account->save();
            $result = $account->toArray();
            $result['workers'] = $accountWorkers;
            Session::set('ACCOUNT', $result,'svip');
         }
        return ['rate'=>$rate,'result'=>$result];
    }
    /**
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     * 返回视频设置
         * {
				container: '.video', //视频容器
                controls:false,//是否显示自带控制栏
	            rightBarShow:false,//是否开启右边控制栏
                timeScheduleAdjust:5,
                title:"松鼠AI物理",
				video:'/storage/20250715/ef337d0501ea4a4c3d791bdaf960b6c7.mp4',//视频地址
                playbackrateList:[0.5,1,1.5,2],
				prompt: [ //提示点
					{
						words: '考点',
						time: 10//时间，单位：秒
					},
					{
						words: '考点',
						time: 20
					}
				]
			}
         */
    public function video($id){
        $info = Knowledge::get($id);
        
        $videoConfig = [
            'container' => '.video', //视频容器
            'controls'=>false,//是否显示自带控制栏
            'rightBarShow'=>false,//是否开启右边控制栏
            'timeScheduleAdjust'=>5,
            'title'=>$info['title'],  //视频标题
            'video'=>$info['video'],//视频地址
            //'seek'=>'cookie',//指定跳转到cookie记录的时间，使用该属性必需配置属性cookie
		    //'cookie'=>md5('video_play_'.$id),//cookie名称 
        ];
        if(!empty($info['exam'])){
            $prompt = json_decode($info['exam'],1);
            foreach ($prompt as $key =>$value){
                $videoConfig['prompt'][] = ['words'=>'考点','time'=>intval($value['times'])];
            }
        }
        
        $this->returnAjax($videoConfig);
        
    }
    protected function returnAjax($data)
    {
        $response = Response::create($data, Config::get('default_ajax_return'));

        throw new HttpResponseException($response);
    }
}
?>